package com.framework.modules.sys.controller;

import com.framework.entity.sys.SysDeptJumpUrl;
import com.framework.exception.util.RespResult;
import com.framework.modules.oss.cloud.OSSFactory;
import com.framework.page.PageUtils;
import com.framework.service.GoodsBannerService;
import com.framework.service.SysDeptJumpUrlService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 商品轮播图
 * @author wq
 */
@RestController
@RequestMapping("/sys/goodsBanner")
public class GoodsBannerController extends AbstractController {

    @Autowired
    private GoodsBannerService goodsBannerService;

    @Autowired
    private SysDeptJumpUrlService sysDeptJumpUrlService;

    /**
     * 商品轮播图列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:goods:list")
    public RespResult querygooodsList(@RequestParam Map<String, Object> params) {
        PageUtils page = goodsBannerService.queryBannerListByGoodsId(params);
        return RespResult.ok().put("page", page);
    }

    /**
     * 删除轮播图
     *
     * @param goodsBannerId
     * @return
     */
    @RequestMapping("/delete/{goodsBannerId}")
    @RequiresPermissions("sys:goods:delete")
    public RespResult deleteBanner(@PathVariable Long goodsBannerId) {
        boolean flag = goodsBannerService.deleteById(goodsBannerId);
        return RespResult.ok().put("flag", flag);
    }

    /**
     * 修改轮播图
     *
     * @param file
     * @param goodsBannerId
     * @param sort
     * @return
     * @throws IOException
     */
    @RequestMapping("/updateBanner")
    @RequiresPermissions("sys:goods:update")
    public RespResult updateBanner(@RequestParam("file") MultipartFile file, @RequestParam("goodsBannerId") Long goodsBannerId, @RequestParam Integer sort) throws IOException {
        Long deptId = getUser().getDeptId();

        SysDeptJumpUrl obj = sysDeptJumpUrlService.queryByDeptIdAndType(deptId,1);
        String prefix=obj.getBannerJump();
        String bannerUrl = "";
        String suffix;
        if (file != null) {
            //上传轮播图
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            bannerUrl = OSSFactory.build().uploadSuffix(file.getBytes(), suffix, prefix);
        }
        Integer count = goodsBannerService.updateBanner(goodsBannerId, bannerUrl, sort);
        return RespResult.ok().put("count", count);
    }

}
